<template>
  <div class="bed-dashboard">

    <header class="dashboard-header">
      <dv-decoration-8 style="width:300px;height:50px;" />
      <div class="title-container">
        <dv-decoration-7 style="width:400px;height:30px;">
          <span class="title-text">病床床位实时概览</span>
        </dv-decoration-7>
      </div>
      <dv-decoration-8 :reverse="true" style="width:300px;height:50px;" />
    </header>

    <div class="controls-container">
      <el-select
          v-model="selectedDepartment"
          placeholder="请选择科室"
          @change="fetchBedData"
          size="large"
          clearable
      >
        <el-option
            v-for="item in departmentOptions"
            :key="item.id"
            :label="item.roomName"
            :value="item.id"
        />
      </el-select>
    </div>

    <el-scrollbar class="main-content-scroll" v-loading="loading">
      <div class="main-content-wrapper">
        <dv-border-box-13
            v-for="ward in wardsData"
            :key="ward.wardId"
            class="ward-outer-box"
        >
          <div class="ward-content-area">
            <div class="ward-header-wrapper">
              <dv-decoration-6 style="width:150px;height:20px;">
                <span class="ward-title-text">{{ ward.wardName }}</span>
              </dv-decoration-6>
            </div>
            <div class="bed-grid">
              <div
                  v-for="bed in ward.beds"
                  :key="bed.bedId"
                  class="bed-card"
                  :class="{ 'occupied': bed.status === 1, 'empty': bed.status === 0 }"
                  @click="onBedClick(bed, ward)"
              >
                <div class="bed-no">{{ bed.bedNo }}</div>
                <div class="bed-status">
                  <span v-if="bed.status === 1">{{ bed.patientName }}</span>
                  <span v-else>空 闲</span>
                </div>
              </div>
            </div>
          </div>
        </dv-border-box-13>
        <div v-if="!selectedDepartment && !loading" class="empty-text">
          请先在顶部选择一个科室
        </div>
      </div>
    </el-scrollbar>

    <el-dialog
        v-model="workstationDialogVisible"
        :title="'护士工作站 - ' + currentPatient.patientName + ' (' + currentPatient.bedNo + ')'"
        width="70%"
        custom-class="data-v-dialog"
        append-to-body
        @close="handleModalClose"
    >
      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">

        <el-tab-pane label="病人信息" name="patientInfo">
          <el-descriptions
              title="患者档案"
              :column="2"
              border
              class="patient-info-descriptions"
          >
            <el-descriptions-item label="姓名">{{ currentPatient.patientName }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ currentPatient.age }} 岁</el-descriptions-item>
            <el-descriptions-item label="性别">
              <span v-if="currentPatient.gender === 1">男</span>
              <span v-else-if="currentPatient.gender === 2">女</span>
              <span v-else>未知</span>
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentPatient.phone }}</el-descriptions-item>
            <el-descriptions-item label="入院科室">{{ currentPatient.roomName }}</el-descriptions-item>
            <el-descriptions-item label="入院病房">{{ currentPatient.wardName }}</el-descriptions-item>
            <el-descriptions-item label="病床号">{{ currentPatient.bedNo }}</el-descriptions-item>
            <el-descriptions-item label="主治医生">{{ currentPatient.doctorName }}</el-descriptions-item>
            <el-descriptions-item label="入院时间" :span="2">{{ currentPatient.admissionDate }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="查看/执行医嘱" name="viewOrders" v-loading="orderLoading">
          <el-table :data="ordersData" max-height="400">
            <el-table-column prop="content" label="医嘱内容" />
            <el-table-column prop="doctorName" label="开立医生" width="120" />
            <el-table-column prop="nurseName" label="执行护士" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status == 0 ? 'warning' : 'success'">
                  {{ scope.row.status == 0 ? '待执行' : '已执行' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                    v-if="scope.row.status == 0"
                    size="small"
                    type="primary"
                    @click="handleExecuteOrder(scope.row.id)"
                >
                  执行医嘱
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="添加护理记录" name="addRecord">
          <el-form :model="newRecordForm" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="体温(℃)">
                  <el-input v-model="newRecordForm.nrTemperature" placeholder="例如: 36.8"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="心率(bpm)">
                  <el-input v-model="newRecordForm.nrPulse" placeholder="例如: 75"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="血压(mmHg)">
              <el-input v-model="newRecordForm.nrBloodpressure" placeholder="例如: 120/80"></el-input>
            </el-form-item>
            <el-form-item label="护理内容">
              <el-input
                  type="textarea"
                  :rows="4"
                  v-model="newRecordForm.nrContent"
                  placeholder="输入护理内容...">
              </el-input>
            </el-form-item>
          </el-form>
          <div style="text-align: right; margin-top: 15px;">
            <el-button type="primary" @click="submitNewRecord">提交</el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="查看护理记录" name="viewRecords" v-loading="recordLoading">
          <el-timeline style="max-height: 500px; overflow-y: auto; padding-top: 10px;">
            <el-timeline-item
                v-for="record in recordsData"
                :key="record.id"
                :timestamp="record.timestamp"
            >
              <p><strong>护士: {{ record.nurseName }}</strong></p>
              <p>体征: 体温 {{ record.temperature }}℃, 血压 {{ record.bloodPressure }}mmHg, 心率 {{ record.pulse }}bpm</p>
              <p>内容: {{ record.content }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>

      </el-tabs>
    </el-dialog>

  </div>
</template>

<script>
// 1. 引入所有需要的组件和API
import { ElMessage, ElMessageBox, ElDialog, ElTag, ElButton, ElSelect, ElOption, ElScrollbar, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElDivider, ElTabs, ElTabPane, ElAlert, ElDescriptions, ElDescriptionsItem, ElRow, ElCol, ElTimeline, ElTimelineItem } from 'element-plus';
import {loadDepartment, loadPatientBed} from "../api/dashboard.js";
// (引入护士站所需的API)
import {addRecord, queryByPatientId, updateRecord} from "../api/doctorOrder.js";
import {addNursingRecord, queryRecordsByPatientId} from "../api/nursingRecord.js";


export default {
  name: "BedDashboardNursing",
  // 3. 注册所有 Element Plus 组件
  components: { ElDialog, ElTag, ElButton, ElSelect, ElOption, ElScrollbar, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElDivider, ElTabs, ElTabPane, ElAlert, ElDescriptions, ElDescriptionsItem, ElRow, ElCol, ElTimeline, ElTimelineItem },

  // 4. 合并 data
  data() {
    return {
      // --- 来自 BedDashboard1.vue ---
      departmentOptions: [],
      selectedDepartment: null,
      wardsData: [],
      loading: false,

      // --- 来自 InpatientNurseStation.vue (弹窗相关) ---
      workstationDialogVisible: false, // (重命名)
      currentPatient: {}, // 关键：当前操作的病人

      // *** 关键改动 ***
      // (设置默认 Tab 为新加的 "病人信息" Tab)
      activeTab: 'patientInfo',

      // Tab: 医嘱
      ordersData: [],
      orderLoading: false,

      // Tab: 添加护理
      newRecordForm: {
        nrTemperature: '',
        nrBloodpressure: '',
        nrPulse: '',
        nrContent: ''
      },

      // Tab: 查看护理
      recordsData: [],
      recordLoading: false,
    };
  },

  // 5. 合并 methods
  methods: {
    // --- BedDashboard1.vue 的方法 ---
    async loadDepartments() {
      try {
        let {data:response} = await loadDepartment();
        if (response && response.code === 200) {
          this.departmentOptions = response.obj;
        } else {
          ElMessage.error(response.message || '获取科室列表失败');
        }
      } catch (error) {
        ElMessage.error('获取科室列表失败，请检查网络。');
      }
    },

    async fetchBedData() {
      let departmentId = this.selectedDepartment;
      if (!departmentId) {
        this.wardsData = [];
        return;
      }
      this.loading = true;
      this.wardsData = [];
      try {
        let {data:response} = await loadPatientBed(departmentId);
        if (response && response.code === 200) {
          this.wardsData = response.obj;
        } else {
          ElMessage.error(response.message || '获取病床数据失败');
        }
      } catch (error) {
        ElMessage.error("获取病床数据失败，请检查网络。");
      } finally {
        this.loading = false;
      }
    },

    // --- 核心改动：合并 onBedClick 和 handleDiagnose ---
    onBedClick(bed, ward) {
      if (bed.status === 0) {
        ElMessage.info(`病床 [${bed.bedNo}] 为空闲`);
        return;
      }
      // (假设后端已升级，bed对象包含了所有信息)
      if (!bed.patientId) {
        ElMessage.error("错误：该床位病人信息不全 (缺少 PatientId)，无法打开工作站。");
        console.error("点击的床位对象 'bed' 缺少 'patientId':", bed);
        return;
      }

      // 组装 currentPatient 对象，包含所有需要显示的信息
      this.currentPatient = {
        // (来自 bed 对象 - 假设后端已升级)
        patientId: bed.patientId,
        patientName: bed.patientName,
        bedNo: bed.bedNo,
        age: bed.age,
        gender: bed.gender,
        phone: bed.phone,
        doctorName: bed.doctorName,
        admissionDate: bed.admissionDate,

        // (来自 ward 对象)
        roomName: ward.roomName,
        wardName: ward.wardName,
      };

      this.workstationDialogVisible = true;
      // 弹窗打开时，不自动加载任何Tab数据，
      // 而是等用户点击时再通过 handleTabClick 按需加载
    },

    // --- InpatientNurseStation.vue 的方法 (移植并修改) ---

    // (弹窗关闭时)
    handleModalClose() {
      this.currentPatient = {};
      this.activeTab = 'patientInfo'; // 重置回病人信息Tab
      // 清空所有Tab的数据
      this.ordersData = [];
      this.recordsData = [];
      this.newRecordForm = { nrTemperature: '', nrBloodpressure: '', nrPulse: '', nrContent: '' };
    },

    // (封装医嘱加载)
    async loadPatientOrders() {
      if (!this.currentPatient.patientId) return;
      this.orderLoading = true;
      try {
        let {data:data} = await queryByPatientId(this.currentPatient.patientId);
        this.ordersData = data.obj;
      } catch (error) {
        ElMessage.error("加载医嘱失败");
      } finally {
        this.orderLoading = false;
      }
    },

    // (封装护理记录加载)
    async loadPatientRecords() {
      if (!this.currentPatient.patientId) return;
      this.recordLoading = true;
      try {
        let {data:data} = await queryRecordsByPatientId(this.currentPatient.patientId);
        // (模拟数据有 timestamp, 真实数据可能需要格式化)
        // (假设 data.obj 返回的数据格式与 InpatientNurseStation.vue 的模拟数据一致)
        this.recordsData = data.obj;
      } catch (error) {
        ElMessage.error("加载护理记录失败");
      } finally {
        this.recordLoading = false;
      }
    },

    // (Tab点击时，按需加载)
    async handleTabClick(tab) {
      const tabName = tab.paneName;

      // 按需加载"医嘱"
      if (tabName === 'viewOrders' && this.ordersData.length === 0) {
        this.loadPatientOrders();
      }

      // 按需加载"查看护理记录"
      if (tabName === 'viewRecords' && this.recordsData.length === 0) {
        this.loadPatientRecords();
      }
    },

    // (执行医嘱)
    async handleExecuteOrder(orderId) {
      try {
        // (您需要实现真实的后端API)
        await updateRecord({
          id: orderId,
          doStatus: 1
        })
        ElMessage.success('医嘱执行成功!');
        // 刷新医嘱列表
        await this.loadPatientOrders();
      } catch (err) {
        ElMessage.error('执行失败');
      }
    },

    // (提交护理记录)
    async submitNewRecord() {
      if (!this.newRecordForm.nrContent) {
        ElMessage.warning('护理内容不能为空');
        return;
      }
      const record = {
        nrCaseId: this.currentPatient.patientId,
        // nurseId 会由后端自动从Token获取
        ...this.newRecordForm,
        nrDate: new Date() // (假设后端需要Date)
      };

      try {
        // (您需要实现真实的后端API)
        let {data:data} = await addNursingRecord(record)
        console.log(data)
        if (data.code === 200){
          ElMessage.success(data.msg)
        }else {
          ElMessage.error(data.msg)
        }
        ElMessage.success('护理记录添加成功!');
        // 重置表单并切换到“查看”Tab
        this.newRecordForm = { nrTemperature: '', nrBloodpressure: '', nrPulse: '', nrContent: '' };
        this.recordsData = []; // 清空旧数据
        this.activeTab = 'viewRecords'; // 自动切换到查看Tab
        await this.loadPatientRecords(); // 重新加载
      } catch (e) {
        ElMessage.error('提交失败');
      }
    },
  },

  created() {
    // 页面加载时只加载科室
    this.loadDepartments();
  }
};
</script>

<style scoped>
/* (所有来自 BedDashboard1.vue 的样式都保留) */
.bed-dashboard {
  width: 100%;
  height: 100%;
  position: relative;
  background: url('https://data-v.oss-cn-hangzhou.aliyuncs.com/uploads/images/3a6f722c1dd14f63b208b5afd6543d88.png') no-repeat center center;
  background-size: cover;
  color: #fff;
  display: flex;
  flex-direction: column;
}
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  height: 80px;
  flex-shrink: 0;
}
.title-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.title-text {
  font-size: 24px;
  font-weight: bold;
  margin: 0 10px;
  color: black;
}
.controls-container {
  padding: 10px 30px;
  text-align: left;
  flex-shrink: 0;
}
.controls-container :deep(.el-select .el-input__wrapper) {
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #0a5a9c;
  box-shadow: none;
}
.controls-container :deep(.el-select .el-input__inner) {
  color: #fff;
}
:global(.el-select-dropdown) {
  z-index: 3000 !important;
}
.main-content-scroll {
  flex: 1;
  padding: 0 30px;
  overflow: auto;
  --el-scrollbar-track-background: rgba(0, 0, 0, 0.2);
  --el-scrollbar-thumb-background: rgba(0, 229, 255, 0.5);
  --el-scrollbar-hover-background: rgba(0, 229, 255, 0.7);
}
.main-content-wrapper {
  padding: 20px 0;
}
.ward-outer-box {
  margin-bottom: 25px;
  padding: 10px;
  background-color: rgba(1, 12, 68, 0.4);
  border-radius: 6px;
}
.ward-content-area {
  padding: 5px 15px 15px 15px;
}
.ward-header-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  margin-bottom: 20px;
}
.ward-title-text {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 5px #00e5ff;
}
.bed-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
  gap: 15px;
  padding: 0 10px;
}
.bed-card {
  height: 90px;
  border: 1px solid;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
}
.bed-card.empty {
  background-color: rgba(22, 160, 133, 0.3);
  border-color: #16a085;
}
.bed-card.empty:hover {
  transform: translateY(-3px) scale(1.03);
  box-shadow: 0 0 18px #16a085;
  background-color: rgba(22, 160, 133, 0.5);
}
.bed-card.occupied {
  background-color: rgba(192, 57, 43, 0.3);
  border-color: #c0392b;
}
.bed-card.occupied:hover {
  transform: translateY(-3px) scale(1.03);
  box-shadow: 0 0 18px #c0392b;
  background-color: rgba(192, 57, 43, 0.5);
}
.bed-no {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
}
.bed-status {
  font-size: 14px;
  margin-top: 5px;
  color: rgba(255, 255, 255, 0.8);
}
.empty-text {
  text-align: center;
  font-size: 20px;
  margin-top: 100px;
  color: rgba(255, 255, 255, 0.7);
}
.patient-info-descriptions {
  margin: 10px;
}

/* (DataV 风格的弹窗样式) */
:global(.data-v-dialog) {
  background-color: rgba(1, 12, 68, 0.9) !important;
  border: 1px solid #00e5ff !important;
  box-shadow: 0 0 20px rgba(0, 229, 255, 0.6) !important;
  color: #fff !important;
  border-radius: 8px !important;
}
:global(.data-v-dialog .el-dialog__header) {
  background-color: rgba(0, 229, 255, 0.2) !important;
  border-bottom: 1px solid rgba(0, 229, 255, 0.5) !important;
  padding: 15px 20px !important;
}
:global(.data-v-dialog .el-dialog__title) {
  color: #00e5ff !important;
  font-weight: bold !important;
  font-size: 18px !important;
}
:global(.data-v-dialog .el-dialog__close) {
  color: #fff !important;
}
/* (弹窗内的Tabs样式) */
:global(.data-v-dialog .el-tabs__content) {
  max-height: 60vh;
  overflow-y: auto;
  color: #fff; /* 确保Tab内容是亮的 */
}
:global(.data-v-dialog .el-tabs--border-card) {
  background: rgba(0, 229, 255, 0.1);
  border: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-tabs--border-card > .el-tabs__header) {
  background-color: rgba(0, 229, 255, 0.2);
  border-bottom: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-tabs__item) {
  color: #eee;
}
:global(.data-v-dialog .el-tabs__item.is-active) {
  color: #00e5ff;
  background: rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table) {
  background-color: transparent;
  color: #fff;
}
:global(.data-v-dialog .el-table tr, .data-v-dialog .el-table th) {
  background-color: transparent;
  color: #fff;
  border-bottom: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table--border::after, .data-v-dialog .el-table--group::after, .data-v-dialog .el-table::before) {
  background-color: rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table__body-wrapper tbody tr:hover > td) {
  background-color: rgba(0, 229, 255, 0.1) !important;
}
:global(.data-v-dialog .el-descriptions__label) {
  color: #00e5ff !important; /* 标签亮蓝色 */
  background: rgba(0, 229, 255, 0.1) !important;
}
:global(.data-v-dialog .el-descriptions__content) {
  color: #ffffff !important; /* 内容白色 */
  background: rgba(0, 229, 255, 0.05) !important;
}
:global(.data-v-dialog .el-descriptions__border .el-descriptions__cell) {
  border: 1px solid rgba(0, 229, 255, 0.3) !important;
}
:global(.data-v-dialog .el-descriptions__title) {
  color: #fff;
  font-weight: bold;
}
.dialog-content-wrapper p {
  line-height: 1.8;
  font-size: 15px;
}
.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
.el-timeline {
  padding-left: 10px;
}
</style>